package taos

import (
	"database/sql"
	"fmt"
	_ "github.com/taosdata/driver-go/v3/taosRestful"
	_ "github.com/taosdata/driver-go/v3/taosWS"
)

type TdEngine struct {
	Link         string
	DriverName   string
	DbName       string
	Database     string
	MaxIdleConns int // 最大空闲连接数
	MaxOpenConns int // 最大连接数
	db           *sql.DB
}

// Connect 连接数据库
func (m *TdEngine) connect() (db *sql.DB, err error) {
	tdDb, err := sql.Open(m.DriverName, m.Link+m.Database)
	if err != nil {
		fmt.Println("failed to connect TDengine, err:", err)
		return
	}
	tdDb.SetMaxIdleConns(m.MaxIdleConns)
	tdDb.SetMaxOpenConns(m.MaxOpenConns)
	m.db = tdDb
	return m.db, nil
}
func (m *TdEngine) Close() {
	if m.db == nil {
		return
	}
	err := m.db.Close()
	if err != nil {
		fmt.Println("failed to close TDengine, err:", err)
		return
	}
	m.db = nil
	//fmt.Println("Closed TdEngine database connection.")
}
func (m *TdEngine) GetDb() (db *sql.DB, err error) {
	if m.db == nil {
		_, err = m.connect()
	}
	return m.db, err
}

// Query 查询
func (m *TdEngine) Query(sql string) (rows *sql.Rows, err error) {
	if m.db == nil {
		_, err = m.connect()
		if err != nil {
			return
		}
	}

	rows, err = m.db.Query(sql)
	if err != nil {
		fmt.Println("failed to query TDengine, err:", err)
		return
	}
	return
}

// Count 统计表中数据条数
func (m *TdEngine) Count(table string) (int, error) {
	if m.db == nil {
		_, err := m.connect()
		if err != nil {
			return 0, err
		}
	}
	sqlStr := "select count(*) as num from " + table
	rows, err := m.db.Query(sqlStr)
	if err != nil {
		fmt.Println("failed to query TDengine, err:", err)
		return 0, err
	}
	var num int
	for rows.Next() {
		err = rows.Scan(&num)
		if err != nil {
			fmt.Println("failed to query TDengine, err:", err)
			return 0, err
		}
	}
	return num, nil
}

func (m *TdEngine) CreateTable(sql string) error {
	if m.db == nil {
		_, err := m.connect()
		if err != nil {
			return err
		}
	}
	_, err := m.db.Exec(sql)
	return err
}
